package com.kzhkwkt.sugoieditor;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;

import android.os.Environment;
import android.util.Log;

public class Exporter {

	private static final String TAG = "Exporter";

	public boolean execute(ActiveFile activeFile) {
		return write(getFilePath(activeFile.getTitle()), activeFile.getContents());
	}

	public boolean execute(String title, String contents) {
		return write(getFilePath(title), contents);
	}

	boolean write(File file, String contents) {
		Log.i(TAG, "Log write Start");
		if(!isWritable()) {
			Log.e(TAG, "SD Card is not writable");
			return false;
		}
		try {
			BufferedWriter bw = new BufferedWriter(
					new OutputStreamWriter(
							new FileOutputStream(file.getPath(), false), "UTF-8"
					)
			);
			bw.write(contents);
			bw.close();
			return true;
		}
		catch(UnsupportedEncodingException e) {
			return false;
		}
		catch(IOException e) {
			return false;
		}
	}

	File getSdCardPath() {
		return Environment.getExternalStorageDirectory();
	}

	File getFilePath(String title) {
		File file = new File(getSdCardPath().getPath() + "/" + title + ".txt");
		if(!file.exists()) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		file.canWrite();
		return file;
	}

	/**
	 * SDカードが書き込み可能を判定する
	 *
	 * @return 書き込み可能 : true / それ以外はfalse
	 */
	boolean isWritable() {
		String state = Environment.getExternalStorageState();
		Log.i(TAG, "SD Card state = " + state);
		return state.equals(Environment.MEDIA_MOUNTED);
	}
}
